#include "XML_Element.h"
#include "commun.h"

#include <iostream>

XML_Element::XML_Element( string name )
{
	this->name = name;
	this->sub_knots = NULL;
	this->attributes = NULL;
}

XML_Element::~XML_Element()
{
	// Destruction des fils :
    while(!sub_knots->empty())
    {
        delete sub_knots->back();
        sub_knots->pop_back();
    }

    delete sub_knots;

    // Destruction des attributs :
    while(!attributes->empty())
    {
        delete attributes->back();
        attributes->pop_back();
    }

    delete attributes;
}

void XML_Element::setSubKnots( vector<XML_Noeud *> * sub_knots )
{
	this->sub_knots = sub_knots;
}

void XML_Element::setAttributes( vector<XML_Attribut *> * attributes )
{
	this->attributes = attributes;
}

string XML_Element::toString( unsigned char depth )
{
	string s = "";
	unsigned char profondeur = depth;

	// Affichage balise ouvrante :
	while ( profondeur > 0 )
	{
		s += ESPACE;
		profondeur--;
	}

	s += '<' + this->name;

	for ( vector<XML_Attribut *>::iterator itAt = attributes->begin() ; itAt != attributes->end() ; itAt++ )
	{
		s += ( * itAt )->toString();
	}

	
	// Si pas de noeud fils -> element "vide"
	if ( this->sub_knots == NULL )
	{
		// Affichage fin balise :
		s += "/>";
		s += '\n';
	}
	else
	{
		// Affichage fin balise :
		s += '>';
		s += '\n';
		
		// Affichage noeud fils :
		for( vector<XML_Noeud*>::const_iterator itKnots = sub_knots->begin() ; itKnots != sub_knots->end() ; itKnots++ )
		{
			s += ( * itKnots )->toString( depth + 1 );
		}
		
		// Affichage balise fermante :
		profondeur = depth;
		while( profondeur > 0 )
		{
			s +=  ESPACE;
			profondeur--;
		}

		s += ("</" + name + ">\n");
	}

	return s;
}

